package com.kzd.gtgame.main.home

import android.content.Context
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.GridLayoutManager
import com.kzd.gtgame.R
import com.kzd.gtgame.custom.setOnClickAntiShakeListener
import com.kzd.gtgame.custom.setTransitionStatusE
import com.kzd.gtgame.jetpack.vm.HomeViewModel
import com.kzd.gtgame.main.game.adapter.GamePresentAdapter
import com.module.lemlin.http.Status
import com.module.lemlin.owner.OwnerViewModeActivity
import kotlinx.android.synthetic.main.activity_home_present.*
import kotlinx.android.synthetic.main.include_app_refresh.*
import kotlinx.android.synthetic.main.include_app_search.*

class HomePresentActivity : OwnerViewModeActivity<HomeViewModel>() {

    private val mGamePresentAdapter = GamePresentAdapter()

    override fun viewModel(): HomeViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_home_present

    override fun stateBar(): StatusBar {
        return StatusBar(color = R.color.white, view = flHomePresentBar)
    }

    override fun initView() {

        rvAppRefreshBody.apply {
            layoutManager = GridLayoutManager(this@HomePresentActivity as Context, (2))
        }.adapter = mGamePresentAdapter

        tvAppSearchSubmit.setOnClickAntiShakeListener {
            viewModel.homePresent(
                keyword = etAppSearchContent.text.toString()
            )
        }

        mSmartRefreshLayout.setOnRefreshListener {
            viewModel.homePresent(
                keyword = etAppSearchContent.text.toString()
            )
        }
        mSmartRefreshLayout.setOnLoadMoreListener {
            viewModel.homePresent(
                keyword = etAppSearchContent.text.toString(),
                isLoadMore = true
            )
        }
    }

    override fun initData() {
        viewModel.homePresent()
    }

    override fun initViewMode() {

        viewModel.homePresentLiveData.observe(this as LifecycleOwner, { response ->
            setTransitionStatusE(response, mGamePresentAdapter, mSmartRefreshLayout)
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            val isLoadMore = response.data?.isLoadMore
                ?: return@observe
            if (isLoadMore) {
                mGamePresentAdapter.addData(data)
            } else {
                mGamePresentAdapter.setNewInstance(data)
            }
        })
    }

}